package cn.westv.scps.web.controller.sysconfig;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.westv.scps.constant.ConfigCodeConstant;
import cn.westv.scps.domain.SysConfig;
import cn.westv.scps.service.sys.config.ISysConfigService;
import cn.westv.scps.utils.Page;
import cn.westv.scps.utils.StringUtils;
import cn.westv.scps.web.controller.base.AbstractController;
import cn.westv.scps.web.controller.sysconfig.vo.ConfigVO;
import cn.westv.scps.web.filter.LoginFilter;

@Controller
@RequestMapping("/sys/config")
public class SysConfigController extends AbstractController<SysConfigController> {
	@Resource
	private ISysConfigService sysConfigService;

	@RequestMapping("/index.cgi")
	public String toIndex_cgi() {
		return "forward:/WEB-INF/page/sys/config/configIndex.jsp";
	}

	@RequestMapping("/edit.cgi")
	public String toEdit_cgi() {
		return "forward:/WEB-INF/page/sys/config/configEdit.jsp";
	}

	/**
	 * 分页查找
	 * 
	 * @param page
	 * @param configVO
	 * @param request
	 * @return
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	@RequestMapping("/list")
	@ResponseBody
	public Map<String, Object> list(Page<SysConfig> page, ConfigVO configVO)
			throws IllegalArgumentException, IllegalAccessException {
		try {
			String hql = "from SysConfig where 1 = 1";
			List<Object> param = new ArrayList<>();
			if (configVO != null) {
				SysConfig config = configVO.getConfig();
				if (config != null) {
					// 反射进行hql拼接
					Field[] fields = config.getClass().getDeclaredFields();
					for (Field field : fields) {
						field.setAccessible(true);
						Object fieldValueObject = field.get(config);
						if (fieldValueObject instanceof String) {
							String fielValue = (String) fieldValueObject;
							if (StringUtils.isNotBlank(fielValue)) {
								hql += "and " + field.getName() + " like ?";
								param.add("%" + fielValue + "%");
							}
						}
					}
				}
			}
			Page<SysConfig> findPage = sysConfigService.findPage(hql, page, SysConfig.class, param.toArray());
			findPage.setUrl("list");
			return ajaxReturnMap(OP_STATUS_SUCCESS, "", findPage);
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 根据Id查找
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/detail")
	@ResponseBody
	public Map<String, Object> detail(String id) {
		if (StringUtils.isEmpty(id)) {
			return ajaxReturnMap(OP_STATUS_FAILD, ConfigCodeConstant.REQUIRED_PARAMETERS_IS_NULL + "（id为空）", null);
		}
		try {
			SysConfig entity = sysConfigService.get(SysConfig.class, id);
			return ajaxReturnMap(OP_STATUS_SUCCESS, "", entity);
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 批量删除
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping("/remove")
	@ResponseBody
	public Map<String, Object> remove(String ids) {
		try {
			String[] idArr = null;
			if (StringUtils.isNotBlank(ids)) {
				idArr = ids.split(","); // 根据id批量删除，id之间使用","分隔
			}
			sysConfigService.delete(SysConfig.class, idArr);
			return ajaxReturnMap(OP_STATUS_SUCCESS, ConfigCodeConstant.DEL_SUCCEED, null);
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 保存或更新
	 * 
	 * @param configVO
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/save")
	@ResponseBody
	public Map<String, Object> save(ConfigVO configVO) throws Exception {
		try {
			String id = "";
			// userId不为空则是修改
			String msg = "";
			SysConfig config = configVO.getConfig();
			if (StringUtils.isNotBlank(config.getId())) {
				// 修改
				id = config.getId();
				SysConfig entityDB = sysConfigService.get(SysConfig.class, id);
				// 复制表单属性
				SysConfig configEntity = config;
				copyBeanNotEmptyFields(entityDB, configEntity);// 将表单对象中的属性，复制到持久类的属性
				// String description = configEntity.getDescription();
				// if (StringUtils.isNotBlank(description)) {
				// entityDB.setDescription(description);
				// }
				// String name = configEntity.getName();
				// if (StringUtils.isNotBlank(name)) {
				// entityDB.setName(name);
				// }
				// String value = configEntity.getValue();
				// if (StringUtils.isNotBlank(value)) {
				// entityDB.setValue(value);
				// }
				sysConfigService.saveOrUpdate(entityDB);
				msg = ConfigCodeConstant.UPDATE_SUCCEED;
			} else {
				// 添加
				SysConfig entity = null;
				entity = configVO.getConfig();
				List<SysConfig> find = sysConfigService.find("from SysConfig where code = ?", SysConfig.class,
						new Object[] { entity.getCode() });// code查询，判断是否存在code重复

				if (find != null && find.size() > 0) {
					msg = "添加失败，code重复！";
				} else {
					entity.setId(null);
					sysConfigService.saveOrUpdate(entity);
					msg = ConfigCodeConstant.ADD_SUCCEED;
				}
			}
			return ajaxReturnMap(OP_STATUS_SUCCESS, msg, null);
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	@RequestMapping("/refresh/urlfilter")
	@ResponseBody
	public Map<String, Object> refreshUrlFilter() {
		try {
			LoginFilter.anon_url = sysConfigService.findByCode(ConfigCodeConstant.ANON_URL).getValue();
			LoginFilter.must_verify_url = sysConfigService.findByCode(ConfigCodeConstant.MUST_VERIFY_URL).getValue();
			return ajaxReturnMap(OP_STATUS_SUCCESS, "更新权限过滤配置成功", null);
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}
}
